package com.news.controller;

import com.news.config.Constant;
import com.news.model.ChannelEntity;
import com.news.service.ChannelService;
import com.news.service.ColumnService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by vitoling on 15/8/18.
 */

@Controller
public class BasicController {

    @Resource
    private ColumnService columnService;
    @Resource
    private ChannelService channelService;

    @RequestMapping("/")
    public String index(Model model){
        List<ChannelEntity> channels = channelService.listAllChannels();
        model.addAttribute("channels",channels);
        return "index";
    }

    @RequestMapping("/test")
    public String test(HttpSession session){

        return "api";
    }

    @RequestMapping("/system/info")
    @ResponseBody
    public Object systemInfo(){

        Map result = new HashMap<>();
        result.put("memory_used", Constant.SERVER_INFO_MEMORY_USED);
        result.put("memory_available",Constant.SERVER_INFO_MEMORY_AVAILABLE);
        result.put("memory_total",Constant.SERVER_INFO_MEMORY_TOTAL);
        result.put("description",Constant.SERVER_INFO_DESCRIPTION);
        result.put("cms_version",Constant.CMS_VERSION);
        return result;
    }

    @RequestMapping("/gotoLogin")
    public String gotoLogin(HttpServletResponse response,HttpServletRequest request){
        // 设置进入登录页面就清除客户端的登录cookie
        Cookie[] cookies = request.getCookies();
        if (null != cookies && cookies.length != 0) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(Constant.Login_User_Cookie_Status_Name)) {
                    cookie.setValue(String.valueOf(Constant.USER_LOGIN_STATUS_DETACHED));
                    response.addCookie(cookie);

                } else {
                    if (cookie.getName().equals(Constant.Login_User_Cookie_Username_Name)) {
                        cookie.setValue(null);
                        response.addCookie(cookie);
                    }
                }
            }
        }
        return "login";
    }

    @RequestMapping("/logout")
    public String logout(){
        return "redirect:gotoLogin";
    }


}
